// utils/feishuApi.js
const appConfig = require('../config/appConfig');
const { tableSchema } = require('../config/tableConfig');

// 获取访问凭证
const getAccessToken = async () => {
  return new Promise((resolve, reject) => {
    tt.request({
      url: 'https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal/',
      method: 'POST',
      data: {
        app_id: appConfig.appId,
        app_secret: appConfig.appSecret
      },
      success(res) {
        if (res.data.code === 0) {
          console.log('Successfully obtained tenant_access_token:', res.data.tenant_access_token);
          resolve(res.data.tenant_access_token);
        } else {
          console.error('Failed to obtain tenant_access_token:', res.data);
          console.log(this.data.app_id);
          console.log(this.data.app_secret);
          reject(res.data);
        }
      },
      fail(err) {
        console.error('Error occurred while requesting tenant_access_token:', err);
        reject(err);
      }
    });
  });
};


/**
 * 在飞书多维表格中查找指定内容
 * @param {string} tableName 表格名称（如：'用户信息表'）
 * @param {string} query 查询条件
 * @returns {Promise<Object|null>} 返回匹配的行数据，查找失败返回 null
 * query构造示例：
 * const query = {
 *  filter: {
 *    "conjunction": "and",
 *    "conditions": [{
 *      "field_name": columnName,
 *      "operator": "is",
 *      "value": [
 *        value
 *        ]
 *      },
 *      ]
 *    }
 * }
 */
 const searchRecord = async (tableName, query) => {
  try {
    const accessToken = await getAccessToken();
    const tableInfo = tableSchema[tableName];
    if (!tableInfo) {
      throw new Error(`Table ${tableName} not found in schema`);
    }
    return new Promise((resolve, reject) => {
      tt.request({
        url: `https://open.feishu.cn/open-apis/bitable/v1/apps/${appConfig.appToken}/tables/${tableInfo.id}/records/search`,
        method: 'POST',
        header: {
          Authorization: `Bearer ${accessToken}`
        },
        data: query,
        success(res) {
          console.log(res)
          if (res.data.data.total != 0) {
            // resolve(getItems(tableName, res.data.data.items));
            resolve(res)
          } else {
            resolve(0)
          }
        },
        fail(err) {
          reject(err);
        }
      });
    });
  } catch (error) {
    console.error('Failed to query table record:', error);
    throw error;
  }
};

function getItems(tableName, res){
  const table = tableSchema[tableName]
  console.log(res)
  datas = []
  for (let i = 0; i < res.length; i++) {
    const item = res[i].fields
    data = {}
    for(let i = 0; i < table.columns.length; i++){ 
      // console.log(`i = ${i}`)
      // console.log(res[table.columns[i]] == true)
      if(item[table.columns[i]]){
        if(table.type[i] == 1){
          data[table.columns[i]] = item[table.columns[i]][0].text
        }else if(table.type[i] == 3 || table.type[i] == 4 || table.type[i] == 5){
          data[table.columns[i]] = item[table.columns[i]]
        }
      }
      
    }
    datas[i] = data
  }
  return datas
}

const searchItems = async (tableName, fieldName) => {
  try {
    const accessToken = await getAccessToken();
    const tableInfo = tableSchema[tableName];
    if (!tableInfo) {
      throw new Error(`Table ${tableName} not found in schema`);
    }
    return new Promise((resolve, reject) => {
      tt.request({
        url: `https://open.feishu.cn/open-apis/bitable/v1/apps/${appConfig.appToken}/tables/${tableInfo.id}/fields`,
        method: 'GET',
        header: {
          Authorization: `Bearer ${accessToken}`
        },
        success(res) {
          console.log('列出字段')
          console.log(res)
          items = []
          data = res.data.data.items
          for (let i = 0; i < data.length; i++) {
            if (data[i].field_name == fieldName) {
              for (let j = 0; j < data[i].property.options.length; j++) {
                items[j] = data[i].property.options[j].name
              }
              break
            }
          }
          resolve(items)
        },
        fail(err) {
          reject(err);
        }
      });
    });
  } catch (error) {
    console.error('Failed to query table record:', error);
    throw error;
  }
};

/**
 * 更新多维表格记录
 * @param {string} tableName 表格名称（如：'用户信息表'）
 * @param {string} recordId 
 * @param {Object} record 要添加的记录（如：['张三', 30]）
 * @returns {Promise<Object|null>} 返回添加的记录数据，添加失败返回 null
 */
const updateRecord = async (tableName, recordId, fields) => {
  try {
    const accessToken = await getAccessToken();
    const tableInfo = tableSchema[tableName];
    if (!tableInfo) {
      throw new Error(`Table ${tableName} not found in schema`);
    }
    // const {columns} = tableSchema[tableName]
    // const items = {}

    // columns.forEach((column, index) => {
    //   items[column] = record[index]
    // })

    console.log("update record: fields: ", fields)
    // console.log(items)

  
    return new Promise((resolve, reject) => {
      tt.request({
        url: `https://open.feishu.cn/open-apis/bitable/v1/apps/${appConfig.appToken}/tables/${tableInfo.id}/records/${recordId}`,
        method: 'PUT',
        header: {
          Authorization: `Bearer ${accessToken}`,
          'Content-Type': 'application/json'
        },
        data: {
          "fields": fields
        },
        success(res) {
          console.log(res);
          if (res.data.code === 0) {
            console.log("updateRecord success")
            resolve(res.data.data.record.fields);  // 返回添加的记录数据
          } else {
            resolve(null);
          }
        },
        fail(err) {
          reject(err);
        }
      });
    });
  } catch (error) {
    console.error('Failed to add table record:', error);
    throw error;
  }
};

/**
 * 往飞书多维表格中添加一条记录
 * @param {string} tableName 表格名称（如：'用户信息表'）
 * @param {Object} record 要添加的记录（如：['张三', 30]）
 * @returns {Promise<Object|null>} 返回添加的记录数据，添加失败返回 null
 */
 const addRecord = async (tableName, record) => {
  try {
    const accessToken = await getAccessToken();
    const tableInfo = tableSchema[tableName];
    if (!tableInfo) {
      throw new Error(`Table ${tableName} not found in schema`);
    }
    const {columns} = tableSchema[tableName];
    const items = {};
    let attachments = [];
    
    columns.forEach((column, index) => {
      if (column == `附件`) {
        attachments = record[index];
      } else {
        items[column] = record[index];
      }
    });

    return new Promise((resolve, reject) => {
      tt.request({
        url: `https://open.feishu.cn/open-apis/bitable/v1/apps/${appConfig.appToken}/tables/${tableInfo.id}/records/`,
        method: 'POST',
        header: {
          Authorization: `Bearer ${accessToken}`,
          'Content-Type': 'application/json'
        },
        data: {
          "fields": items
        },
        success(res) {
          if (res.data.code === 0) {
            const record_id = res.data.data.record.record_id;
            console.log()

            // 上传其他字段成功，上传附件
            if (attachments && attachments.length > 0) {
              sendAttachmentsToServer(attachments)
                .then((fileTokens) => {
                  const fields = { "附件": fileTokens };
                  updateRecord(tableName, record_id, fields)
                    .then((upres) => {
                      if (upres !== 0) {
                        resolve(res.data.data.fields);
                      } else {
                        reject('Failed to update record');
                      }
                    }).catch(reject);
                }).catch(reject);
            } else {
              resolve(res.data.data.fields);
            }
          } else {
            resolve(null);
          }
        },
        fail(err) {
          reject(err);
        }
      });
    });
  } catch (error) {
    console.error('Failed to add table record:', error);
    throw error;
  }
};

// 发送附件数据到服务器
const sendAttachmentsToServer = async (attachments) => {
  console.log('sendAttachmentsToServer: attachments:', attachments);
  
  file_tokens = []
  for (let i = 0; i < attachments.length; i++){
    token = await sendAttachmentToServer(attachments[i])
    file_tokens[i] = {"file_token": token}
  }
  console.log('file_tokens:', file_tokens)
  return file_tokens
};

const sendAttachmentToServer = async(attachment) => {
  console.log('current attachment:', attachment)

  file_path = attachment.tempFilePath
  file_name = file_path.split('/').pop()
  content_type = getContentType(file_name)
  console.log('current attachment\'s path:', file_path)
  console.log('current attachment\'s name:', file_name)
  console.log('current attachment\'s content type:', content_type)
  // return 'AClnb7UYboJ46SxV4SwcTzlsntb'
  
  // try {
  //   const response = await tt.request({
  //     url: 'http://43.138.64.157:5000/upload',  // 服务器接口URL
  //     method: 'POST',
  //     header: {
  //       'Content-Type': content_type,  // 检查是否需要不同的 Content-Type
  //     },
  //     data: {
  //       attachment: attachment,
  //     }
  //   });

    // await tt.uploadFile({
    //   url: 'http://43.138.64.157:5000/upload', // 替换为你的服务器地址
    //   filePath: file_path,
    //   name: file_name,
    //   success(res) {
    //     console.log("tt.uploadFile res:", res)
    //     const data = JSON.parse(res.data);
    //     console.log("data:", data)
    //     if (data.success) {
    //       tt.showToast({ title: '上传成功', icon: 'success' });
    //     } else {
    //       tt.showToast({ title: '上传失败', icon: 'none' });
    //     }
    //   },
    //   fail(err) {
    //     console.log("upload attachment failed")
    //     tt.showToast({ title: '上传失败', icon: 'none' });
    //     console.error(err);
    //   }
    // });
    const uploadTask = tt.uploadFile({
      // 替换为需要上传的url
      "url": 'http://43.138.64.157:5000/upload',
      "filePath": file_path,
      "name": file_name,
      "header": {
        "content-type": "multipart/form-data"
      },
      success (res) {
      // upload Start
        console.log('update success: ', res)
      },
      fail (res) {
      // uploadFile Failed
        console.log('update failed: ', res)
      }
    })

  //   console.log('Server Response:', response);  // 查看响应的内容
  //   if (response && response.data) {
  //     console.log('Response Data:', response.data);  // 检查 data 是否存在
  //     if (response.status_code == 200) {
  //       console.log('current attachment\'s file_token:', response.data.file_token)
  //       return response.data.file_token;  // 返回服务器返回的 file_token
  //     } else {
  //       throw new Error('Failed to upload attachments. Server responded with failure.');
  //     }
  //   } else {
  //     throw new Error('Response data is undefined or missing.');
  //   }
  // } catch (err) {
  //   console.error('Error during attachment upload:', err);  // 输出详细错误信息
  //   throw new Error('Failed to upload attachments');
  // }
  console.log("lkp attachment")
};

// 根据文件名获取对应的Content-Type类型
function getContentType(fileName) {
  // 常见图片类型
  const imageExtensions = {
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.png': 'image/png',
    '.gif': 'image/gif',
    '.bmp': 'image/bmp',
    '.tiff': 'image/tiff',
    '.heif': 'image/heif',
    '.webp': 'image/webp',
  };

  // 常见视频类型
  const videoExtensions = {
    '.mp4': 'video/mp4',
    '.mov': 'video/quicktime',  // Apple 的 MOV 文件
    '.avi': 'video/x-msvideo',
    '.webm': 'video/webm',
    '.mkv': 'video/x-matroska',
    '.3gp': 'video/3gpp',  // 3GP 格式，安卓设备常见
    '.flv': 'video/x-flv',
  };

  // 获取文件扩展名
  const ext = fileName.toLowerCase().slice(fileName.lastIndexOf('.'));

  // 判断并返回对应的 Content-Type
  if (imageExtensions[ext]) {
    return imageExtensions[ext];
  } else if (videoExtensions[ext]) {
    return videoExtensions[ext];
  } else {
    return 'application/octet-stream';  // 默认为未知文件类型
  }
}

module.exports = {
  searchRecord,
  searchItems,
  updateRecord,
  addRecord,
  getItems,
};
